from django.http import HttpResponse


class IPBlockMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        #定义一个IP列表,@todo后续配置到数据库中
        self.block_ips=['localhost']

    def __call__(self, request):
        print("============访问了中间件 IPBlock middleware===========")
        #过滤IP
        ip = request.META.get('REMOTE_ADDR')
        print("ip:",ip)
        if ip in self.block_ips:
            #终止请求，alert提醒
            return HttpResponse("<script>alert('您的IP地址已被封禁！');window.location.href='/';</script>")

        response = self.get_response(request)
        return response